package com.imooc.mmall.common;

import com.imooc.mmall.pojo.User;
import com.imooc.redis.RedisPoolUtil;
import com.imooc.utils.CookieUtil;
import com.imooc.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * spring 拦截器
 */
@Slf4j
public class AuthorityInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		//请求controller中的方法名
		HandlerMethod handlerMethod = (HandlerMethod)handler;
		//解析HandlerMethod
		String methodName = handlerMethod.getMethod().getName();
		String className = handlerMethod.getBean().getClass().getSimpleName();

		//对于登录请求不拦截，直接放行
		if(StringUtils.equals(className,"UserController") && StringUtils.equals(methodName,"login")){
			return true;
		}

		//验证用户是否登陆
		User user = null;
		String loginToken  = CookieUtil.readLoginToken(request);
		if(StringUtils.isNotEmpty(loginToken)){
//			String userJsonStr = RedisShardedPoolUtil.get(loginToken);
			String userJsonStr = RedisPoolUtil.get(loginToken);
			user = JsonUtil.string2Obj(userJsonStr,User.class);
		}
		//此处需处理登陆了是否有权限
		if(user != null){
			//此处应继续验证权限
			return true;
		}else{
			response.sendRedirect("/login.html");
			return false;
		}




//		StringBuffer requestParamBuffer = new StringBuffer();
//		Map paramMap = request.getParameterMap();
//		Iterator it = paramMap.entrySet().iterator();
//		while (it.hasNext()) {
//			Map.Entry entry = (Map.Entry) it.next();
//			String mapKey = (String) entry.getKey();
//			String mapValue = "";
//			//request的这个参数map的value返回的是一个String[]
//			Object obj = entry.getValue();
//			if (obj instanceof String[]){
//				String[] strs = (String[])obj;
//				mapValue = Arrays.toString(strs);
//			}
//			requestParamBuffer.append(mapKey).append("=").append(mapValue);
//		}
//		log.info("权限拦截器拦截到请求,className:{},methodName:{},param:{}",className,methodName,requestParamBuffer);
//
//
//		//验证用户是否登陆
//		User user = null;
//		String loginToken  = CookieUtil.readLoginToken(request);
//		if(StringUtils.isNotEmpty(loginToken)){
//			String userJsonStr = RedisShardedPoolUtil.get(loginToken);
//			user = JsonUtil.string2Obj(userJsonStr,User.class);
//		}
//		//此处需处理登陆了是否有权限
//		if(user != null){
//			return true;
////			/**
////			 * 此处默认返回无权限，后续引入spring shiro
////			 * */
////			response.reset();//geelynote 这里要添加reset，否则报异常 getWriter() has already been called for this response
////			response.setCharacterEncoding("UTF-8");
////			response.setContentType("application/json;charset=UTF-8");
////			PrintWriter out = response.getWriter();
////			Map resultMap = Maps.newHashMap();
////			resultMap.put("success",false);
////			resultMap.put("msg","你无权限！");
////			out.print(JsonUtil.obj2String(resultMap));
////			out.flush();
////			out.close();
////			return  false;
//		}else{
//			response.reset();//geelynote 这里要添加reset，否则报异常 getWriter() has already been called for this response
//			response.setCharacterEncoding("UTF-8");
//			response.setContentType("application/json;charset=UTF-8");
//			PrintWriter out = response.getWriter();
//			Map resultMap = Maps.newHashMap();
//			resultMap.put("success",false);
//            resultMap.put("msg","请先登录！");
//			out.print(JsonUtil.obj2String(resultMap));
//			out.flush();
//			out.close();
//			return  false;
//		}
	}


	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		//System.out.println("postHandle");
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		//System.out.println("afterCompletion");
	}

}
